<template>
  <div>
    <el-row :gutter="20">
      <el-col :xs='12' :sm="12" :md="8" :lg="6" :xl="6" v-for="(t, index) in biopsyList" :key="index">
        <el-card
          style="margin-top: 10px"
          :body-style="{ padding: '0px' }"
          shadow="hover"
          class="card-content"
        >
          <el-row type="flex" justify="center">
            <img
              :src="imageServiceURL+t.labelUrl"
              @click="exclude(t)"
              style="width: 100%; height: 230px; object-fit: contain;"
              alt="切片标签图"
            />
          </el-row>
          <div style="display: flex;align-items: center;height: 30px;width:100%;margin:0 auto;margin-top:5px;justify-content: space-between;">
            <div style="font-size: 0.95rem;">
              序号：{{ t.id }}
              <div class="card-time">{{ t.createTime }}</div>
              </div>
            <div>
              <el-button
                class="card-button"
                icon="el-icon-edit"
                size="mini"
                @click="biopsyMatch(t)"
              ></el-button>
              <el-button
                class="card-button"
                icon="el-icon-delete"
                size="mini"
                @click="biopsyRemove(t)"
              ></el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row style="margin-top: 10px" align="right">
      <el-pagination
        :page-sizes="[9, 12, 15]"
        @current-change="pageJumpTo"
        @size-change="sizeChange"
        :current-page="pageInfo.page"
        :page-size="pageInfo.size"
        :total="pageInfo.total"
        style="text-align: center; margin-top: 12px;"
        layout="sizes, prev, pager, next, total"
      ></el-pagination>
    </el-row>
    <el-dialog
      class="abow-dialog"
      :close-on-click-modal="false"
      title="切片匹配"
      @close="closeDialog"
      :visible.sync="matchDialog.visible"
      width="80%"
    >
      <el-row style="margin-top: 60px">
        <el-col :span="12" class="search-style">
          <el-form label-width="80px" label-position="left">
            <el-form-item label="病理编号">
              <el-input
                v-model="matchDialog.pathologyId"
                placeholder="请输入病理编号"
                class="input-form"
                size="mini"
              ></el-input>
              <el-button @click="ljMatchSearch" type="primary" size="mini">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="10">
          <div class="image-box" ref="IMAGE_SERVICE" @click="imagePinwheel($event)">
            <img
              :src="imageServiceURL + labelUrl"
              title="鼠标左键点击可顺时针旋转90度"
              style="width: 350px; height: 150px;"
              alt="切片标签图"
            />
          </div>
        </el-col>
      </el-row>
      <diagnosis-detail
        ref="diagnosisDetail"
        :diagnosis="diagnosis"
        :isAdvancedSetting="isAdvancedSetting"
      ></diagnosis-detail>
      <span slot="footer" class="dialog-footer">
        <el-button @click="matchSave" type="primary" size="mini" :loading="saveLoading">保存</el-button>
        <el-button @click="matchDialog.visible = false" size="mini">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment/moment';
import DiagnosisDetail from '@templates/components/DiagnosisMatchDetail';
import diagnosisDefault from '@templates/diagnosisDefault';
import _ from 'lodash';

export default {
  name: 'DiagnosisScanUnMatched',
  components: {
    DiagnosisDetail
  },

  data() {
    return {
      currentDeg: 0,
      saveLoading: false, //页面保存时loading状态
      imageServiceURL: process.env.ImageServiceURL, // 图片服务器地址
      labelUrl: '', // 标签图地址
      biopsyId: '',
      scanStatus: {
        biopsyHistoryId: 0
      },
      biopsyList: [],
      pageInfo: {
        total: 0,
        size: 12,
        page: 1
      },
      organList: [],

      matchDialog: {
        visible: false,
        pathologyId: ''
      },

      diagnosis: diagnosisDefault,
      isAdvancedSetting: false,
      biopsyRequestInterval: null,
      ageUnitKindList: [],
      checkCategoryList: [],
      patientCategoryList: [],

      dictRequestMap: [
        {
          code: 'checkCategory',
          arrayKey: 'checkCategoryList'
        },
        {
          code: 'patientCategory',
          arrayKey: 'patientCategoryList'
        },
        {
          code: 'ageUnitKind',
          arrayKey: 'ageUnitKindList'
        }
      ],
      slicePurposeClone: '',
      sliceCategoryClone: ''
    };
  },
  mounted() {
    this.biopsyListRequest();
    this.dictionariesRequest();
    this.biopsyRequestInterval = window.setInterval(
      this.biopsyListRequest,
      5000
    );
  },
  beforeDestroy() {
    // 移除监听回车按键
    const _this = this;
    document.removeEventListener('keydown', _this.watchEnter);
  },
  methods: {
    closeDialog() {
      this.currentDeg = 0;
      this.$refs.IMAGE_SERVICE.style.transform = `rotate(${this.currentDeg}deg)`;
      this.matchDialog.visible = false;
    },
    // 图片旋转
    imagePinwheel(e) {
      this.currentDeg += 90;
      this.$refs.IMAGE_SERVICE.style.transform = `rotate(${this.currentDeg}deg)`;
    },
    //跳转到切片浏览器
    exclude(val) {
      const { state } = this.$store;
      const { href } = this.$router.resolve({
        name: 'Viewer',
        path: '/Viewer',
        query: {
          fileName: val.newFilename,
          originFilename: val.originFilename,
          pathologyId: 'null',
          biopsyId: val.id,
          authorization: this.$store.state.authorization,
          userId: state.user.id
        }
      });
      const width = window.screen.availWidth + 10;
      const height = window.screen.availHeight + 10;
      window.open(
        href,
        'doctorWorkstation',
        `location=no,width=${width},height=${height}`
      );
    },
    async biopsyListRequest() {
      await this.$axios({
        // 详见 axios 请求配置项
        method: 'GET',
        url: '/PROXY-Remote/biopsy/list/forNoUploadAndNoMatch',
        params: {
          currentLevel: 4,
          page: this.pageInfo.page - 1,
          size: this.pageInfo.size
        }
      }).then(res => {
        // 请求失败
        if (res.data.code !== 200) {
          throw new Error(res.data);
        }

        // 请求成功
        const result = res.data;
        // 分页信息
        this.pageInfo = {
          total: result.pageInfo.total,
          page: result.pageInfo.page + 1,
          size: result.pageInfo.size
        };
        // 查询结果数据
        this.biopsyList = [];
        result.data.forEach((t, index) => {
          const item = t;
          item.index = index;
          item.uploadStatusName = t.status ? '上传中' : '未上传';
          this.biopsyList.push(item);
        });
      });
    },
    // 匹配切片
    biopsyMatch(item) {
      this.labelUrl = item.labelUrl;
      this.biopsyId = item.id;
      // 表单数据初始化
      this.diagnosis = _.clone(diagnosisDefault);
      this.diagnosis.slicePurpose = item.slicePurpose;
      this.diagnosis.sliceCategory = item.sliceCategory;
      this.diagnosis.branchId = item.branchId;
      this.diagnosis.branchName = item.branchName;

      this.slicePurposeClone = item.slicePurpose;
      this.sliceCategoryClone = item.sliceCategory;

      if (item.pathologyId !== '' || item.pathologyId !== null) {
        this.matchDialog.pathologyId = item.pathologyId;
      }
      //增加监听事件
      const _this = this;
      document.addEventListener('keydown', _this.watchEnter);
      // this.diagnosis.age = '';
      this.diagnosis.ifShowSetting = true;
      this.matchDialogOpen();
    },
    //监听事件
    watchEnter(e) {
      const keyNum = window.event ? e.keyCode : e.which; // 获取被按下的键值
      const altKey = e.altKey;
      if (keyNum === 13) {
        this.ljMatchSearch();
        e.preventDefault();
      }
    },
    // 移除切片
    biopsyRemove(t) {
      this.$confirm('删除该切片, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            await this.$axios({
              // 详见 axios 请求配置项
              method: 'DELETE',
              url: `/PROXY-Remote/biopsy/${t.id}`
            }).then(res => {
              // 请求失败
              if (res.data.code !== 200) {
                throw new Error(res.data);
              }

              // 请求成功
              // const result = res.data.data;
              this.$message.success('删除成功!');
              if (this.biopsyList.length === 1) {
                if (this.pageInfo.page > 1) {
                  this.pageInfo.page -= 1;
                }
              }
              this.biopsyListRequest();
            });
          } catch (e) {
            // 跳出
          }
        })
        .catch(() => {});
    },
    // 页数跳转
    pageJumpTo(page) {
      this.pageInfo.page = page;
      this.biopsyListRequest();
    },
    // 每页显示数量改变
    sizeChange(size) {
      this.pageInfo.size = size;
      this.biopsyListRequest();
    },
    matchDialogOpen() {
      this.organsRequest();
      this.setDefaultValue();
      this.matchDialog.visible = true;
    },
    // 获取字典信息
    async dictionariesRequest() {
      await this.dictRequestMap.forEach(map => {
        this.$axios({
          method: 'GET',
          url: '/PROXY-Remote/dicts/list',
          params: {
            code: map.code,
            page: 0,
            size: 99
          }
        }).then(res => {
          if (res && res.data.code === 200) {
            this[map.arrayKey] = _.clone(res.data.data);
          }
        });
      });
    },
    // 设置默认值
    setDefaultValue() {
      if (this.ageUnitKindList.length > 0) {
        this.diagnosis.ageUnit = this.ageUnitKindList[0].id;
      }
      if (this.checkCategoryList.length > 0) {
        this.diagnosis.checkCategory = this.checkCategoryList[0].id;
      }
      if (this.patientCategoryList.length > 0) {
        this.diagnosis.patientCategory = this.patientCategoryList[0].id;
      }
    },
    // 搜索
    async matchSearch() {
      try {
        await this.$axios({
          // 详见 axios 请求配置项
          method: 'GET',
          url: `/PROXY-Remote/biopsy/search/${this.matchDialog.pathologyId}`
        }).then(res => {
          // 请求失败{
          if (res.data.code !== 200) {
            this.$message.warning('查找失败');
            throw new Error(res.data);
          } else {
            // 请求成功
            const result = res.data.data;
            if (!result) {
              this.$message.warning('查找失败');
              return;
            }

            // 数据安全结构化
            Object.keys(this.diagnosis).forEach(key => {
              if (typeof this.diagnosis[key] === 'string') {
                this.diagnosis[key] = _.get(result, key, '');
              } else if (typeof this.diagnosis[key] === 'number') {
                this.diagnosis[key] = _.get(result, key, 0);
              } else if (this.diagnosis[key] instanceof Array) {
                this.diagnosis[key] = _.clone(result[key]);
              } else if (this.diagnosis[key] instanceof Object) {
                this.diagnosis[key] = _.get(result, key, {
                  name: ''
                });
              } else {
                this.diagnosis[key] = _.get(result, key, '');
              }

              // this.diagnosis.attachment = _.get(result, 'attachmentList', []);
              this.diagnosis.currentLevel = 0;
              if (this.diagnosis[key] === null) {
                this.diagnosis[key] = '';
              }
              const count = parseInt(this.diagnosis.age, 10);
              this.diagnosis.age = count;
              if (this.diagnosis.ageUnit === 0) {
                this.diagnosis.ageUnit = this.ageUnitKindList[0].id;
              }
              if (this.diagnosis.checkCategory === 0) {
                this.diagnosis.checkCategory = '';
              }
              if (this.diagnosis.patientCategory === 0) {
                this.diagnosis.patientCategory = '';
              }
            });

            this.$message.success('查找成功');
          }
        });
      } catch (e) {
        console.log('e', e);
        // 跳出
      }
    },
    // 朗家模拟 搜索
    ljMatchSearch() {
      try {
        this.$axios({
          // 详见 axios 请求配置项
          method: 'post',
          url: `/PROXY-Remote/diagnosis/info/?pathologyId=${this.matchDialog.pathologyId}`
        }).then(res => {
          // 请求失败{
          if (res.data.code !== 200) {
            this.$message.warning('查找不到此人信息');
            throw new Error(res.data);
          }
          // 请求成功
          const result = res.data.data;
          console.log('result', result);
          if (result === null) {
            this.$message.warning('查找不到此人信息');
            this.diagnosis = _.clone(diagnosisDefault);
            // this.diagnosis.attachment = [];
            return;
          }

          console.log(this.diagnosis.sampleOrganId);
          // 数据安全结构化
          console.log('this.diagnosis', this.diagnosis);
          Object.keys(this.diagnosis).forEach(key => {
            if (typeof this.diagnosis[key] === 'string') {
              this.diagnosis[key] = _.get(result, key, '');
            } else if (typeof this.diagnosis[key] === 'number') {
              this.diagnosis[key] = _.get(result, key, 0);
            } else if (this.diagnosis[key] instanceof Array) {
              this.diagnosis[key] = [];
            } else if (this.diagnosis[key] instanceof Object) {
              this.diagnosis[key] = _.get(result, key, {
                name: ''
              });
            } else {
              this.diagnosis[key] = _.get(result, key, '');
            }
            //this.diagnosis.attachment = [];
            //this.diagnosis.attachment = _.get(result, 'attachmentList', []);
            this.diagnosis.currentLevel = 0;
            if (this.diagnosis[key] === null) {
              this.diagnosis[key] = '';
            }
            const count = parseInt(this.diagnosis.age, 10);
            this.diagnosis.age = count;
            if (this.diagnosis.ageUnit === 0) {
              this.diagnosis.ageUnit = this.ageUnitKindList[0].id;
            }
            if (this.diagnosis.checkCategory === 0) {
              this.diagnosis.checkCategory = '';
            }
            if (this.diagnosis.patientCategory === 0) {
              this.diagnosis.patientCategory = result.patientCategory;
              // this.diagnosis.patientCategory = '';
            } else {
              this.diagnosis.patientCategory = 531;
            }
            this.diagnosis.slicePurpose = this.slicePurposeClone;
            this.diagnosis.sliceCategory = this.sliceCategoryClone;
          });
          this.diagnosis['biopsyInfo'] = result.biopsyInfo;
          this.diagnosis['biopsySumCount'] = result.biopsySumCount;
          console.log('this.diagnosis1', this.diagnosis);
          this.$message.success('查找成功');
        });
      } catch (e) {
        console.log('e', e);
        // 跳出
      }
    },
    // 保存 TODO：附件
    async matchSave() {
      const flag = this.$refs.diagnosisDetail.validateForm('baseInfoForm');
      console.log('flag', flag);
      const biopsyData = { biopsyId: this.biopsyId };
      const diagnosisData = _.assignIn({}, this.diagnosis, biopsyData);
      let specimenTypeCopy = diagnosisData.specimenType;
      // 诊断三项高级设置处理
      if (!this.isAdvancedSetting) {
        delete diagnosisData.needFirstVisit;
        delete diagnosisData.needSkipSubmit;
        delete diagnosisData.canFinalVerify;
      }
      // console.log('diagnosisData.attachment'+diagnosisData.attachment);
      // if (diagnosisData.attachment.length > 0) {
      //   delete diagnosisData.attachment;
      // }

      flag
        .then(async () => {
          this.saveLoading = true;
          await this.$axios({
            // 详见 axios 请求配置项
            method: 'POST',
            url: '/PROXY-Remote/biopsy/match',
            data: diagnosisData
          }).then(res => {
            this.saveLoading = false;
            // 请求失败{
            if (res.data.code !== 200) {
              this.$message.warning('匹配失败');
              throw new Error(res.data);
            }

            // if (this.diagnosis.attachment.length > 0) {
            //   this.diagnosis.attachment.forEach((attachment) => {
            //     const item = attachment;
            //     item.diagnosisId = res.data.data.id;
            //     this.attachmentUpload(item);
            //   });
            // }
            // 请求成功
            this.$message.success('匹配成功');
            // 表单数据初始化
            this.diagnosis = _.clone(diagnosisDefault);
            this.diagnosis.specimenType = specimenTypeCopy;
            this.diagnosis.attachment = [];
            this.matchDialog.pathologyId = '';
            this.matchDialog.visible = false;
            this.$emit('getAngelCount');
            this.biopsyListRequest();
          });
        })
        .catch(e => {
          console.log('e-2', e);
        });
    },
    // 获取脏器数据
    async organsRequest() {
      try {
        await this.$axios({
          // 详见 axios 请求配置项
          method: 'GET',
          url: '/PROXY-Remote/organs',
          params: {
            size: 10000
          }
        }).then(res => {
          // 请求失败
          if (res.data.code !== 200) {
            throw new Error(res.data);
          }

          // 请求成功
          const result = res.data;
          this.organList = [];
          // 查询结果数据
          result.data.forEach(t => {
            const item = t;
            if (item.body) {
              item.bodyList = item.body.split(' ');
            } else {
              item.bodyList = [];
            }
            this.organList.push(item);
          });
        });
      } catch (e) {
        console.log('e', e);
        // 跳出
      }
    },
    async attachmentUpload(attachment) {
      try {
        await this.$axios({
          method: 'POST',
          url: '/PROXY-Remote/attachment',
          data: attachment
        });
      } catch (e) {
        throw new Error(e);
      }
    }
  },
  destroyed() {
    if (this.biopsyRequestInterval) {
      clearInterval(this.biopsyRequestInterval);
      this.biopsyRequestInterval = null;
    }
  }
};
</script>

<style scoped>
.card-content {
 /* width: 360px;*/
  width:100%;
  height: 280px;
  padding: 10px;
  box-sizing: border-box;

}

.card-time {
  color: rgba(165, 165, 172, 0.5);
  font-size: 0.75rem;
}

.card-button {
  float: right;
  display: inline-flex;
  margin: 0;
  border: 0;
  width: 25px;
  justify-content: center;
  align-items: center;
}

.image-box {
  /*display: flex;*/
  /*padding: 10px;*/
  /*justify-content: right;*/
  right: 20px;
  position: absolute;
  top: -70px;
}

.abow-dialog >>> .el-dialog__body {
  height: 600px;
  overflow-y: scroll;
}

.search-style {
  position: relative;
  top: -30px;
}
</style>
